<template>
  <div class="exam-share container">
    <div class="share-header">
      <div class="title">试卷验证</div>
      <div class="info">进入考试需进行验证，验证成功即可进入考试</div>
    </div>
    <div class="share-body">
      <template v-if="steps == 1">
        <i class="el-icon-warning user-icon"></i>
        <div class="user-prompt">很抱歉！签名错误，不能进行考试</div>
        <el-button type="primary" @click="toHome">返回首页</el-button>
      </template>

      <el-button v-else-if="steps == 2" type="primary" @click="toLogin">去登录</el-button>

      <template v-else-if="steps == 3">
        <i class="el-icon-warning user-icon"></i>
        <div class="user-prompt">很抱歉！您未在白名单上，不能进行考试</div>
        <el-button type="primary" @click="toHome">返回首页</el-button>
      </template>

      <div v-else-if="steps == 4" class="verify-view">
        <div class="title">验证码</div>
        <div class="input">
          <el-input v-model="value" placeholder="请输入试卷验证码"></el-input>
          <el-button type="primary" :disabled="codeBtnDisabled" @click="handleSubmitForm"
            >立即验证</el-button
          >
        </div>
      </div>

      <template v-else-if="steps == 5">
        <el-image
          :src="require('@/assets/images/public/face_placeholder.png')"
          class="face-img"
        ></el-image>
        <el-button type="primary" @click="handleFaceEntrance">人脸验证</el-button>
      </template>

      <el-button v-else-if="steps == 6" type="primary" @click="toTopic">去考试</el-button>
    </div>

    <!-- 人脸验证 -->
    <EduFaceVerify
      v-if="faceVisible"
      :visible.sync="faceVisible"
      scene_key="exam"
      :scene_id="routeQueryData.id"
      :scene_type="1"
      @cancel="handleFaceSuccess"
    ></EduFaceVerify>
  </div>
</template>

<script>
/* 参数名	类型	是否必需参数	说明
n	number	是	作答次数 0表示不限制
f	number	否	是否开启人脸认证 1: 是 ，否则该参数不存在
u	array	否	白名单用户id列表，为空时该参数不存在
c	string	否	验证码，最大长度为6，为空时该参数不存在
st	number	否	考试开始时间，JS时间戳，为空时该参数不存在
et	number	否	考试结束时间，JS时间戳，为空时该参数不存在
sg_t	string	是	签名 TIMESTAMP时间戳
sg_n	string	是	签名 NONCE随机字符串
sg_s	string	是	签名字符串 SIGN

分享考试在用户端的验证流程是：是否登录、白名单、验证码，用户访问的时候，
先判断登录，登录后再判断是否在白名单内，最后输入验证码，人脸，进入考试
*/

import md5 from 'spark-md5'
import signature from '@/utils/signature.js'
import { mapGetters } from 'vuex'
import EduFaceVerify from '@/components/EduFaceVerify'
import debounce from '@/utils/throttle.js'
export default {
  components: {
    EduFaceVerify
  },
  data() {
    return {
      steps: 0, // 步骤
      value: '', // 验证码
      faceVisible: false, // 人脸验证框
      routeQueryData: {}
    }
  },
  computed: {
    ...mapGetters({
      isLogin: 'user/isLogin',
      accountInfo: 'user/accountInfo',
      faceStatus: 'projectSetting/getGlobFaceStatus' // 是否已认证人脸
    }),
    codeBtnDisabled() {
      return this.$util.isEmpty(this.value)
    }
  },
  methods: {
    init() {
      const userInfo = this.accountInfo
      const query = this.$route.query
      const array = ['id', 'n', 'f', 'u', 'c', 'st', 'et']
      const params = this.getParamsData(query, array) // 接口验证参数
      this.routeQueryData = query
      const sign = signature(params, query.sg_t, query.sg_n) // 签名
      // 第一步 验证签名
      if (sign['E-APP-SIGN'] != query.sg_s) {
        this.steps = 1
      }
      // 第二步 未登录
      else if (!this.isLogin) {
        this.toLogin()
        this.steps = 2
      }
      // 第三步 白名单
      else if (this.$util.isDef(params.u) && !params.u.includes(userInfo.id)) {
        this.steps = 3
      }
      // 第四步 验证码
      else if (this.$util.isDef(params.c)) {
        this.steps = 4
      }
      // 第五步 人脸
      else if (this.$util.isDef(params.f) && params.f == 1) {
        this.steps = 5
        this.handleFaceEntrance()
      } else {
        this.steps = 6
      }
    },
    getParamsData(query, array) {
      let params = {} // 接口验证参数
      for (let i in query) {
        array.forEach(k => {
          if (i == k) params[i] = query[i]
        })
      }
      return params
    },
    // 验证码
    handleSubmitForm() {
      const params = this.routeQueryData
      let code = md5.hash(this.value)
      if (params.c === code) {
        // 验证成功是否需要人脸
        if (this.$util.isDef(params.f) && params.f == 1) {
          this.steps = 5
        } else {
          this.toTopic()
        }
      } else {
        this.$message.error('验证码错误')
      }
    },
    // 人脸提示弹窗
    handleFaceEntrance() {
      // 已认证
      if (this.faceStatus) {
        this.faceVisible = true
      } else {
        this.$messageBox
          .confirm('未完成人脸认证，请先去认证', {
            type: 'none',
            center: true,
            confirmButtonText: '去认证'
          })
          .then(() => {
            this.$router.push({
              path: '/my/profile/face_verify',
              query: {
                back: 1
              }
            })
          })
          .catch(() => {})
      }
    },
    // 人脸验证成功
    handleFaceSuccess() {
      this.toTopic()
    },
    // 考试
    async toTopic() {
      debounce(async () => {
        const query = this.routeQueryData
        const exam = await this.$api.getExamPaperBase({ paper_id: query.id }, res => res.data)
        const timestamp = new Date().getTime() // 时间戳
        const lowerBound = Math.round(query.st) || null // 下限时间戳
        const upperBound = Math.round(query.et) || null // 上限时间戳
        //  n 可考次数 screen_cut 已考试次数
        if (
          this.$util.isDef(query.n) &&
          Number(query.n) > 0 &&
          query.n <= exam.examination_answer_count
        ) {
          this.$message.info('考试次数已用完')
        } else if (lowerBound && lowerBound > timestamp) {
          this.$message.info('暂未开放')
        } else if (upperBound && upperBound < timestamp) {
          this.$message.info('暂未开放')
        } else {
          this.$router.push({
            path: '/exam/paper/topic',
            query: {
              id: query.id,
              s: 1
            }
          })
        }
      }, 2000)
    },
    // 去登录
    toLogin() {
      this.$globalToLogin()
    },
    // 去首页
    toHome() {
      this.$router.push({
        path: '/'
      })
    }
  },
  mounted() {
    this.init()
  }
}
</script>

<style lang="scss" scoped>
.exam-share {
  margin-top: 10px;
  .share-header {
    height: 159px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-image: url(~@assets/images/public/examverify_top_bg.png);
    .title {
      font-size: 28px;
      font-weight: bold;
      color: $text-color-import;
      letter-spacing: 2px;
    }
    .info {
      margin-top: 20px;
      font-size: 14px;
      font-weight: 400;
      color: $text-color-secondary;
    }
  }
  .share-body {
    background: #ffffff;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 500px;
    .user-icon {
      color: #dcdfe6;
      font-size: 40px;
    }
    .user-prompt {
      margin-top: 20px;
      margin-bottom: 60px;
      font-size: 14px;
      font-weight: 500;
      color: $text-color-import;
    }
    .verify-view {
      width: 420px;
      .title {
        font-size: 15px;
        font-weight: 500;
        color: $text-color-import;
      }
      .input {
        display: flex;
        margin-top: 15px;
        .el-input {
          flex: 1;
          min-width: 0;
        }
        .el-button {
          margin-left: 20px;
        }
      }
    }
    .face-img {
      margin-bottom: 40px;
    }
  }
}
</style>
